package cn.itcast.web.aspect;
import java.util.Date;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect     // 指定当前类为切面类
@Component  // 创建对象
public class LogAspect {

    @Autowired
    private SysLogService logService;
    @Autowired
    private HttpServletRequest request;


    /**
     * 在执行控制器方法之后，自动记录日志到日志表中
     */
    @Around("bean(*Controller) && !bean(sysLogController)")
    public Object insertLog(ProceedingJoinPoint pjp){
        try {
            // 执行控制器方法，获取控制器方法的返回值
            Object retV = pjp.proceed();

            // 自动记录日志
            SysLog log = new SysLog();
            log.setIp(request.getRemoteAddr());
            log.setTime(new Date());
            log.setMethod(pjp.getSignature().getName());
            log.setAction(pjp.getTarget().getClass().getName());
            User loginUser = (User) request.getSession().getAttribute("loginInfo");
            if (loginUser != null) {
                log.setUserName(loginUser.getUserName());
                log.setCompanyId(loginUser.getCompanyId());
                log.setCompanyName(loginUser.getCompanyName());
            }
            // 记录日志
            logService.save(log);
            return retV;
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}
